package com.example.demo.grbkxt.servlet;

import com.example.demo.grbkxt.mapper.UserMapper;
import com.example.demo.grbkxt.model.User;
import com.example.demo.grbkxt.util.MyBatisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            User user = mapper.findByUsername(username);

            if (user != null && password.equals(user.getPassword())) {
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("user", user);

                if (user.isAdmin()) {
                    response.sendRedirect(request.getContextPath() + "/blog/admin");
                } else {
                    response.sendRedirect(request.getContextPath() + "/blog/user");
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/login.jsp?error=1");
            }
        }
    }
}
